var randomID = (new Date()).valueOf();;
var config = {
    /** 用户授权配置 */
    authConfig: {
        // REST API 访问地址 https://console.easemob.com/app/im-service/detail 
        baseUrl : 'a1.easemob.com', 
        // APPKEY https://console.easemob.com/app/applicationOverview/detail 
        orgName : '1113181124010841', 
        // APPKEY https://console.easemob.com/app/applicationOverview/detail 
        appName : 'cloudstudio',    

        clientId: 'YXA6KMsxsO--EeiNQJmhf8gr3w',

        clientSecret: 'YXA6FBHoX7zcDwmO49D6PB7AbB3TjqY',
    },

    /** 连接配置 */
    connectConfig:{
        //  连接地址 https://console.easemob.com/app/generalizeMsg/overviewService
        host : 'rmwzi0.cn1.mqtt.chat', 
        // WebSocket 协议服务端口，如果是走 HTTPS，设置443端口
        port: 443 ,     
        // APPID  https://console.easemob.com/app/generalizeMsg/overviewService 
        appId: 'rmwzi0',  
        //  用户自定义deviceID
        deviceId :'song_'+randomID,
        // clientId 格式 deviceID@AppID
        clientId : 'song_'+randomID+'@rmwzi0', //

        // 是否走加密 HTTPS，如果走 HTTPS，设置为 true
        useTLS : true, 
        // cleansession标志
        cleanSession : true, 
        // 超时重连时间
        reconnectTimeout : 2000, 
        // 请求超时时间
        timeout: 2, 
        // mqtt版本号
        mqttVersion: 4, 
    },
}
var client = new easemobMQTT(config);
var username = 'user';
var password = 'user';
var clientId = 'mikutap_client_'+randomID;
var topic = 'mikutap';



client.onMessageArrived = function(message){

    var receive_topic = message.destinationName;
    var receive_content = message.payloadString;
        receive_content = JSON.parse(receive_content);
    if(receive_content.clientId != clientId){
        var e = jQuery.Event("keydown"); //模拟一个键盘事件
        e.which = receive_content.key;
        e.keyCode = receive_content.keyCode;
        $('*').trigger(e); //模拟按键
    }

    console.log('接收到消息:');
    console.log(receive_content);
}

client.onConnectionSuccess = function(message){
    console.log('连接成功')
    client.subscribe(topic);
}

client.login(username,password);
client.connect();



$('*').bind('keyup',function(e){
    client.sendMessage(topic,JSON.stringify({
        'key':e.key,
        'keyCode':e.keyCode,
        'clientId':clientId,
    }));
});